/**
 * 
 */
package com.swg.cocobox.filetransfer.data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import com.swg.cocobox.server.ReaderServer;

/**
 * @author satriaprayoga
 *
 */
public class DataReceiver extends ReaderServer{
	
	private FileOutputStream output;
	private TransferResponse response;

	public DataReceiver(InetAddress address, int port) throws IOException {
		super(address, port);
	}
	
	public synchronized boolean processResponse(TransferResponse response){
		this.response=response;
		this.notify();
		return true;
	}

	@Override
	protected synchronized void read(SelectionKey key) throws IOException {
		SocketChannel socketChannel=(SocketChannel)key.channel();
		if(response!=null){
			output=new FileOutputStream(response.getResponseFile());
			FileChannel fileChannel=output.getChannel();
			ByteBuffer readBuffer=ByteBuffer.allocate(response.getFileSize());
			readBuffer.clear();
			int numRead;
		//	int total=0;
			while((numRead=socketChannel.read(readBuffer))>0){
				readBuffer.flip();
				while(readBuffer.hasRemaining()){
					fileChannel.write(readBuffer);
				}
			//	total+=numRead;
				//System.out.println("saving: "+total);
				readBuffer.clear();
			}
			fileChannel.close();
			output.flush();
			output.close();
			response.setComplete(true);
			if(numRead==-1){
				key.cancel();
				key.channel().close();
				return ;
			}
		}
		
	}

	

}
